package cc.javaee.bbs.tool;

import org.apache.commons.io.FileUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author xdw
 */
public class FileUpload {

    public static String upload(MultipartFile file) throws IOException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //保存文件到临时目录
        String context = request.getSession().getServletContext().getRealPath("/");

        String dirs = "/uploadTempDirectory/";

        File dir = new File(context + dirs);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String originalFilename = file.getOriginalFilename();
        int lastIndex = originalFilename.lastIndexOf(".");
        String suffix = "";
        if (lastIndex != -1) {
            suffix = originalFilename.substring(lastIndex);
        }
        String fileName = StringUtil.getShortUUID() + suffix;

        String savePath = context + dirs + fileName;
        File saveFile = new File(savePath);
        file.transferTo(saveFile);

        //页面显示用户上传的图片
//        FileUtils.readFileToByteArray(saveFile);
        return dirs + fileName;
    }
}
